package com.lzx.iteam;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.lzx.iteam.adapter.SubDialogListAdapter;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.AttendanceClassData;
import com.lzx.iteam.bean.ElasticClassData;
import com.lzx.iteam.bean.ElasticUserData;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.DateUtil;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.widget.CHScrollView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

import static android.R.attr.data;
import static android.R.attr.id;
import static android.R.attr.key;
import static com.baidu.location.b.k.cl;
import static com.lzx.iteam.DialerApp.mContext;
import static com.lzx.iteam.DialerApp.map;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 11月 25日
 * Time: 下午4:11
 *
 * @QQ : 1234567890
 * **********************************
 *
 * 排班表格 数据编辑页面
 */
public class AttendanceSubClassExcleActivity extends MyBaseActivity implements View.OnClickListener{


    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.ch_scroll_sub_class_excle)
    private CHScrollView mScrollViewDate;
    @FindViewById(id = R.id.ll_sub_class_excle_date)
    private LinearLayout mLayoutDate;
    @FindViewById(id = R.id.lv_sub_class_excle)
    private ListView mListView;

    //方便测试，直接写的public
    public HorizontalScrollView mTouchView;

    private List<CHScrollView> mHScrollViews = new ArrayList<>();
    private ArrayList<Map<String,Object>> mData = new ArrayList<>();
    private ArrayList<Long> mDates = new ArrayList<>();
    private ArrayList<AttendanceClassData> mSubClass = new ArrayList<>();
    private Map<String,Object> mClicksubClass; // 点击的数据
    private ElasticUserData mUserData;
    private MyAdapter mAdapter;

    private String mGroupId;
    private String mFormId;
    private String mGroupName;
    private String mUserType;
    private String mContactId;
    private int mPositionX = -1;
    private int mPositionY = -1;
    private int mPositionClass = -1;
    private int mSetStatus = -1;  //处理方式 1.新增,2.编辑,0.删除
    private long mOneDayTime = 24 * 60 * 60; // 一天的秒数
    private boolean mFlagLeft;
    private long mTodayDate;


    private final int REQUEST_CODE_SUB_CREATE = 200;
    private final int SUB_CLASS_LIST = 30000;
    private final int SUB_CLASS_SET = 30001;
    private final int SUB_BEFORE_CLASS_LIST = 30002;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
            switch (msg.what){
                case SUB_CLASS_LIST:
                    CHScrollView.firstRight = true;
                    if (msg.arg1 == 0){
                        if(mDates.size() == 60){
                            return;
                        }
                        if (msg.obj != null){
                            JSONObject object = (JSONObject) msg.obj;
                            try {
                                JSONObject data = object.getJSONObject("data");
                                JSONObject sub = data.getJSONObject("sub_attendances");
                                Iterator it = sub.keys();
                                List<String> keyListstr = new ArrayList<String>();
                                while(it.hasNext()){
                                    keyListstr.add(it.next().toString());
                                }
                                for (int i = 0; i < keyListstr.size(); i++) {
                                    Map<String,Object> map = new HashMap<>();
                                    String key = keyListstr.get(i);
                                    int index = key.lastIndexOf(":");
                                    String name = key.substring(0,index);
                                    String attenadanceId = key.substring(index + 1);

                                    if(mAdapter == null){
                                        mUserData = new ElasticUserData();
                                        mUserData.setName(name);
                                        mUserData.setAttendance_id(attenadanceId);
                                        map.put("user",mUserData);
                                        Map<String,ElasticClassData> classDatas = new HashMap();
                                        JSONArray array = sub.getJSONArray(key);
                                        if (array.length() > 0){
                                            for (int j = 0; j < array.length(); j++) {
                                                JSONObject classData = array.getJSONObject(j);
                                                ElasticClassData classBean = new ElasticClassData();
                                                String date = classData.getString("date");
                                                classBean.setDate(date);
                                                classBean.setSub_attendance_id(classData.getString("sub_attendance_id"));
                                                classBean.setSub_form_id(classData.getString("sub_form_id"));
//                                            classBean.setContact_id(classData.getString("contact_id"));
                                                classDatas.put(date,classBean);
                                            }
                                        }
                                        map.put("classes",classDatas);
                                        mData.add(map);
                                    }else{
                                        JSONArray array = sub.getJSONArray(key);
                                        if (array.length() > 0){
                                            for (int j = 0; j < array.length(); j++) {
                                                JSONObject classData = array.getJSONObject(j);
                                                ElasticClassData classBean = new ElasticClassData();
                                                String date = classData.getString("date");
                                                classBean.setDate(date);
                                                classBean.setSub_attendance_id(classData.getString("sub_attendance_id"));
                                                classBean.setSub_form_id(classData.getString("sub_form_id"));
//                                            classBean.setContact_id(classData.getString("contact_id"));
                                                ((Map<String,ElasticClassData>)mData.get(i).get("classes")).put(date,classBean);
                                            }
                                        }
                                    }

                                }
                                if(mAdapter == null){
                                    mAdapter = new MyAdapter();
                                    mListView.setAdapter(mAdapter);
                                }else{
                                    setDateLayout(mDates.get(mDates.size() - 1) + mOneDayTime);
                                }
                                mAdapter.bindData(mData);
                                waitDlgDismiss();
                            } catch (JSONException e) {
                                Log.e("My_Exception"," ====  " + e.toString());
                            }
                        }

                    }else{
                        waitDlgDismiss();
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case SUB_BEFORE_CLASS_LIST:
                    CHScrollView.firstLeft = true;
                    if (msg.arg1 == 0){
                        if (msg.obj != null){
                            mData.clear();
                            JSONObject object = (JSONObject) msg.obj;
                            try {
                                JSONObject data = object.getJSONObject("data");
                                JSONObject sub = data.getJSONObject("sub_attendances");
                                Iterator it = sub.keys();
                                List<String> keyListstr = new ArrayList<String>();
                                while(it.hasNext()){
                                    keyListstr.add(it.next().toString());
                                }
                                for (int i = 0; i < keyListstr.size(); i++) {
                                    Map<String,Object> map = new HashMap<>();
                                    String key = keyListstr.get(i);
                                    int index = key.lastIndexOf(":");
                                    String name = key.substring(0,index);
                                    String attenadanceId = key.substring(index + 1);

                                    mUserData = new ElasticUserData();
                                    mUserData.setName(name);
                                    mUserData.setAttendance_id(attenadanceId);
                                    map.put("user",mUserData);
                                    Map<String,ElasticClassData> classDatas = new HashMap();
                                    JSONArray array = sub.getJSONArray(key);
                                    if (array.length() > 0){
                                        for (int j = 0; j < array.length(); j++) {
                                            JSONObject classData = array.getJSONObject(j);
                                            ElasticClassData classBean = new ElasticClassData();
                                            String date = classData.getString("date");
                                            classBean.setDate(date);
                                            classBean.setSub_attendance_id(classData.getString("sub_attendance_id"));
                                            classBean.setSub_form_id(classData.getString("sub_form_id"));
                                            classDatas.put(date,classBean);
                                        }
                                    }
                                    map.put("classes",classDatas);
                                    mData.add(map);
                                }
                                setDateLayout(mDates.get(0) - mOneDayTime * 7);
                                mAdapter.bindData(mData);
                                mFlagLeft = false;
                                waitDlgDismiss();
                            } catch (JSONException e) {
                                Log.e("My_Exception"," ====  " + e.toString());
                            }
                        }

                    }else{
                        waitDlgDismiss();
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case SUB_CLASS_SET:
                    if(msg.arg1 == 0){
                        if (mSetStatus == 0){ // 删除
                            ((Map<String,ElasticClassData>)(mData.get(mPositionY).get("classes"))).remove(mDates.get(mPositionX) + "");
                            mAdapter.bindData(mData);
                            waitDlgDismiss();
                        }else if(mSetStatus == 1 || mSetStatus == 2){ // 新增 | 编辑
                            JSONObject object = (JSONObject) msg.obj;
                            String sub_attendance_id = "";
                            try {
                                JSONObject data = object.getJSONObject("data");
                                sub_attendance_id = data.getString("sub_attendance_id");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            ElasticClassData elasticClassData = new ElasticClassData();
                            elasticClassData.setSub_form_id(mSubClass.get(mPositionClass).get_id());
                            elasticClassData.setSub_attendance_id(sub_attendance_id);
                            elasticClassData.setDate(mDates.get(mPositionX) + "");
                            ((Map<String,ElasticClassData>)(mData.get(mPositionY).get("classes"))).put(mDates.get(mPositionX) + "",elasticClassData);
                            mAdapter.bindData(mData);
                            waitDlgDismiss();
                        }
                    }else{
                        waitDlgDismiss();
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState,R.layout.sub_class_excle_layout);
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mTvRight.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mTvTitle.setText("点击表格修改排班");
        mTvRight.setText("增加班次");
        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mFormId = intent.getStringExtra("form_id");
        mGroupName = intent.getStringExtra("group_name");
        mUserType = intent.getStringExtra("user_type");
        mContactId = intent.getStringExtra("contact_id");
        String subForms = intent.getStringExtra("sub_class");

        if(!StringUtil.isEmpty(subForms)){
            try {
                JSONArray jsonArray = new JSONArray(subForms);
                mSubClass.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject sub = jsonArray.getJSONObject(i);
                    AttendanceClassData data = new AttendanceClassData();
                    data.setSub_name(sub.getString("sub_name"));
                    data.set_id(sub.getString("_id"));
                    data.setIs_quartic(sub.getInt("is_quartic"));
                    data.setStart_work_time(sub.getString("start_work_time"));
                    data.setEnd_work_time(sub.getString("end_work_time"));
                    if (sub.getInt("is_quartic") == 1){
                        data.setNoon_end_time(sub.getString("noon_end_time"));
                        data.setNoon_start_time(sub.getString("noon_start_time"));
                    }
                    mSubClass.add(data);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (mSubClass == null) {
            mSubClass = new ArrayList<>();
        }

        mTodayDate = getDayBegin();
        setDateLayout(mTodayDate);
        mHScrollViews.add(mScrollViewDate);
        getSubClassList(mTodayDate);

    }

    /**
     * 设置日期
     */
    private void setDateLayout(long firstTime){

        if(mFlagLeft){
            mDates.clear();
            mLayoutDate.removeAllViews();
        }

        for (int i = 0; i < 30; i++) {
            long time = firstTime + mOneDayTime * i;
            mDates.add(time);
            TextView tv = new TextView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Constants.dip2px(this, 79.4f), Constants.dip2px(this, 40));
            tv.setGravity(Gravity.CENTER);
            tv.setLayoutParams(params);
            tv.setText(DateUtil.getSubClassDate(time * 1000));
            tv.setTextColor(getResources().getColor(R.color.black));
            mLayoutDate.addView(tv);
            View line = new View(mActivity);
            LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 0.6f), Constants.dip2px(mContext, 40));
            line.setLayoutParams(lineParams);
            line.setBackgroundResource(R.color.excle_line);
            mLayoutDate.addView(line);
        }
    }
    /**
     * 滑动中
     * @param l
     * @param t
     * @param oldl
     * @param oldt
     */
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
        for (CHScrollView scrollView : mHScrollViews) {
            if (mTouchView != scrollView)
            scrollView.smoothScrollTo(l, t);
        }

    }

    /**
     * 滑动到最右侧
     */
    public void onScrollRight(){
        // 防止连续加载更多
        if(mDates.size() == 30){
            getSubClassList(mDates.get(mDates.size() - 1) + mOneDayTime);
        }
    }

    /**
     * 滑动到最左侧
     */
    public void onScrollLeft(){
        // 防止连续加载更多
        if(!mFlagLeft){
            getBeforeSubClassList(mDates.get(0) - 7 * mOneDayTime);
        }
    }

    /**
     * 获取所有排班数据
     */
    private void getSubClassList(long time){
        waitDlgShow();
        mFlagLeft = false;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_FORM_ID, mFormId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_STATUS, "1"));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DATE, time + ""));

        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(SUB_CLASS_LIST));
        msg.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_ELASTIC_LIST;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }

    /**
     * 获取所有排班数据
     */
    private void getBeforeSubClassList(long time){
        waitDlgShow();
        mFlagLeft = true;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_FORM_ID, mFormId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_STATUS, "1"));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DATE, time + ""));

        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(SUB_BEFORE_CLASS_LIST));
        msg.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_ELASTIC_LIST;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }

    /**
     * 设置排班数据
     */
    private void setSubClass(){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_FORM_ID, mFormId));

        if(mPositionX == -1 || mPositionY == -1){
            return;
        }else{
            ElasticUserData userData = (ElasticUserData) mClicksubClass.get("user");
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_ID, userData.getAttendance_id()));

            Map<String,ElasticClassData> classDatas = (Map<String, ElasticClassData>) mClicksubClass.get("classes");
            ElasticClassData classData = classDatas.get(mDates.get(mPositionX) + "");

            if(mSetStatus == 0){
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SUB_ATTENDANCE_ID, classData.getSub_attendance_id()));
            }else if(mSetStatus == 1){
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SUB_FORM_ID, mSubClass.get(mPositionClass).get_id()));
            }else if (mSetStatus == 2){
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SUB_ATTENDANCE_ID, classData.getSub_attendance_id()));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SUB_FORM_ID, mSubClass.get(mPositionClass).get_id()));
            }else{
                return;
            }
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_STATUS, mSetStatus + ""));
        if(mSetStatus == 1){
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DATE, mDates.get(mPositionX) + ""));
        }

        if(mSetStatus != -1){
            waitDlgShow();
        }
        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(SUB_CLASS_SET));
        msg.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_ELASTIC_SET;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);
    }


    /**
     * 获取当天的日期时间戳
     * @return
     */
    public long getDayBegin() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 001);
        return cal.getTimeInMillis()/1000;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_ll_back:
                toAttendanceCreateActivity();
                break;
            case R.id.title_tv_right:
                createNewShift();
                break;

        }
    }

    class MyAdapter extends BaseAdapter{

        private int x = -1;
        private int y = -1;
        ArrayList<Map<String,Object>> mData;

        public MyAdapter() {

        }

        public void bindData(ArrayList<Map<String,Object>> data){
            mData = data;
            notifyDataSetChanged();
        }
        public void setSelectItemBackground(int x , int y){
            this.x = x;
            this.y = y;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mData == null ? 0:mData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            if(convertView == null){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.sub_class_lv_item_layout,null);
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_excle_item);
                holder.layoutScroll = (CHScrollView) convertView.findViewById(R.id.ch_scroll_excle_item);
                holder.layoutSub = (LinearLayout) convertView.findViewById(R.id.ll_excle_item);
                convertView.setTag(holder);

            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            Map<String,Object> classes = mData.get(position);
            ElasticUserData user = (ElasticUserData) classes.get("user");
            holder.tvName.setText(user.getName());

            holder.layoutSub.removeAllViews();
            for (int i = 0; i < mDates.size(); i++) {
                long date = mDates.get(i);
                TextView tv = new TextView(mContext);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 79.4f), Constants.dip2px(mContext, 40));
                tv.setGravity(Gravity.CENTER);
                tv.setLayoutParams(params);
                tv.setTextColor(getResources().getColor(R.color.black));

                /*if (i == x && position == y){
                    tv.setBackgroundColor(getResources().getColor(R.color.excle_bg));
                }else{
                    if (position%2 == 0){
                        tv.setBackgroundColor(getResources().getColor(R.color.excle_bg));
                    }else{
                        tv.setBackgroundColor(getResources().getColor(R.color.white));
                    }
                }*/

                HashMap<String,ElasticClassData> subClass = (HashMap<String, ElasticClassData>) classes.get("classes");
                if(subClass != null){
                    ElasticClassData data = subClass.get(date + "");
                    if (data != null) {
                        for (int j = 0; j < mSubClass.size(); j++) {
                            if(data.getSub_form_id().equals(mSubClass.get(j).get_id())){
                                tv.setText(mSubClass.get(j).getSub_name());
                                break;
                            }
                        }
                    }else{
                        tv.setText("");
                    }

                }else{
                    tv.setText("");
                }

                if(date > mTodayDate){
                    if (position%2 == 0){
                        tv.setBackgroundResource(R.color.excle_bg);
                    }else{
                        tv.setBackgroundResource(R.color.white);
                    }
                    tv.setOnClickListener(new MyClickLinstener(i,position,true));
                }else{
                    tv.setBackgroundResource(R.color.color_aaa);
                    tv.setOnClickListener(new MyClickLinstener(i,position,false));
                }
                holder.layoutSub.addView(tv);
                View line = new View(mActivity);
                LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 0.6f), Constants.dip2px(mContext, 40));
                line.setLayoutParams(lineParams);
                line.setBackgroundResource(R.color.excle_line);
                holder.layoutSub.addView(line);

            }

            if (position%2 == 0){
//                holder.layoutScroll.setBackgroundResource(R.color.excle_bg);
                holder.tvName.setBackgroundResource(R.color.excle_bg);
            }else{
//                holder.layoutScroll.setBackgroundResource(R.color.white);
                holder.tvName.setBackgroundResource(R.color.white);
            }
            if (!mHScrollViews.isEmpty()) {
                int size = mHScrollViews.size();
                final int scrollX = mScrollViewDate.getScrollX();
                //第一次满屏后，向下滑动，有一条数据在开始时未加入
                if (scrollX != 0) {
                    final ViewHolder finalHolder = holder;
                    mListView.post(new Runnable() {
                        @Override
                        public void run() {
                            //当listView刷新完成之后，把该条移动到最终位置
                            finalHolder.layoutScroll.scrollTo(scrollX, 0);
                        }
                    });
                }
            }
            mHScrollViews.add(holder.layoutScroll);
            return convertView;
        }

        class ViewHolder{
            private TextView tvName;
            private LinearLayout layoutSub;
            private CHScrollView layoutScroll;
        }
    }


    class MyClickLinstener implements View.OnClickListener {

        private int y_position;    // x 列数
        private int x_position;    // y 行数
        private boolean isCanEdit; // 是否可编辑

        public MyClickLinstener(int x_position,int y_position,boolean edit) {
            this.x_position = x_position;
            this.y_position = y_position;
            this.isCanEdit = edit;
        }

        @Override
        public void onClick(View view) {
            mPositionX = x_position;
            mPositionY = y_position;
            if(isCanEdit){
                if(mSubClass == null || (mSubClass != null && mSubClass.size() == 0)){
                    showSubDialog(0);
                }else{
                    mClicksubClass = mData.get(mPositionY);
                    Map<String,ElasticClassData> classDatas = (Map<String, ElasticClassData>) mClicksubClass.get("classes");
                    ElasticClassData classData = classDatas.get(mDates.get(mPositionX) + "");
                    if(classData == null){
                        showSubDialog(1);
                    } else{
                        showSubDialog(2);
                    }
                }
            }else{
                Toast.makeText(mActivity, "班次不可编辑", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * @param type  0:无班次  1：还没设置排班  2： 修改排班
     *
     */
    private void showSubDialog(final int type){
        final AlertDialog dialog = new AlertDialog.Builder(this)
              .create();
        dialog.show();
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.dimAmount = 0.4f; // TODO 设置黑暗度  0.0f完全不暗，1.0f全暗
//        lp.alpha = 0.5f; // TODO 设置透明度    0.0f完全透明，1.0完全不透明
        window.setAttributes(lp);
        // 设置布局
        window.setContentView(R.layout.sub_dialog_layout);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        // 设置弹出的动画效果
//		window.setWindowAnimations(R.style.bottomStyle);

        ListView listView = (ListView) window.findViewById(R.id.lv_sub_dialog);
        SubDialogListAdapter adapter = new SubDialogListAdapter(mActivity,mSubClass);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                dialog.dismiss();
                mPositionClass = position;
                mSetStatus = type;
                setSubClass();
            }
        });

        View cancelLayout = window.findViewById(R.id.view_sub_cancel);
        cancelLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        TextView tvRestOrNull = (TextView) window.findViewById(R.id.tv_sub_dialog);
        View line = window.findViewById(R.id.view_sub_dialog);
        if(type == 0){
            tvRestOrNull.setVisibility(View.VISIBLE);
            line.setVisibility(View.VISIBLE);
            tvRestOrNull.setText("暂未设置班次");
        } else if(type == 1){
            tvRestOrNull.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
        }else{
            tvRestOrNull.setVisibility(View.VISIBLE);
            line.setVisibility(View.VISIBLE);
            tvRestOrNull.setText("休息");
        }
        tvRestOrNull.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if(type == 2){ // 删除
                    mSetStatus = 0;
                    setSubClass();
                }else{
                    mSetStatus = -1;
                }
            }
        });

    }

    /**
     * 创建新的班次
     */
    public void createNewShift(){
        if (mSubClass.size() >= 20){
            Toast.makeText(mActivity, "最多可设置二十个班次", Toast.LENGTH_SHORT).show();
        }else{
            Intent intent = new Intent(this,AttendanceSubClassEditActivity.class);
            intent.putExtra("position",-1);
            intent.putExtra("group_id",mGroupId);
            intent.putExtra("form_id",mFormId);
            intent.putExtra("sub_classes",mSubClass);
            startActivityForResult(intent,REQUEST_CODE_SUB_CREATE);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK){
            if(requestCode == REQUEST_CODE_SUB_CREATE){
                AttendanceClassData backData = (AttendanceClassData) data.getSerializableExtra("sub_class");
                mSubClass.add(backData);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        toAttendanceCreateActivity();
        super.onBackPressed();
    }

    /**
     * 跳转到考勤列表页面
     */
    private void toAttendanceCreateActivity(){
        Intent intent = new Intent(mActivity, AttendanceCreateActivity.class);
        intent.putExtra("group_id", mGroupId);
        intent.putExtra("group_name", mGroupName);
        intent.putExtra("user_type", mUserType);
        intent.putExtra("contact_id", mContactId);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

}
